package com.sphd.emanu.activity.pointcommondity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;
import com.sphd.emanu.adapter.CommondityAdapter;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.permission.Moudle;
import com.sphd.emanu.pojo.goods.Category;
import com.sphd.emanu.pojo.goods.Commodity;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.utils.PermissionConfig;
import com.wzutils.L;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 积分商品列表
 *
 * @Author Hu
 * @Time 2017/6/23 -- 14:22.
 * @Email 87683202@qq.com
 */
public class PointCommondityActivity extends MVPBaseActivity<PointCommondityContract.View, PointCommondityPresenter> implements PointCommondityContract.View {
    Intent intent;
    Bundle bundle;
    User user;
    @BindView(R.id.add_point_commntiy)
    TextView addPointCommntiy;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_recycler)
    RecyclerView myRecycler;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    private CommondityAdapter commondityAdapter;
    private AlertDialog editCommdityDialog;
    View listDialog;
    TextView editCommdityName;
    MaterialEditText editCommdityPointe;
    LinearLayout layoutCommdityName;
    Button cancle, confirm;
    boolean isUpdate = false;
    private Commodity commodity;
    Integer commodityId = 0;
    boolean isCanDo = false;
    List<Moudle> moudles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_point_commondity);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        mySwf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                addData();
            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(editCommdityPointe.getText().toString().trim())) {
                    toast("积分不能为空");
                } else {
                    if (isUpdate) {
                        showProgressDialog();
                        mPresenter.updatePointsCommondity(commodity.getMaterialId(), commodityId,
                                Integer.valueOf(editCommdityPointe.getText().toString().trim()));
                    } else {
                        if (commodityId != 0) {
                            showProgressDialog();
                            mPresenter.addPointsCommondity(commodityId,
                                    Integer.valueOf(editCommdityPointe.getText().toString().trim()));
                        } else {
                            toast("请选择商品后确定");
                        }
                    }
                }
            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editCommdityDialog.dismiss();
            }
        });
        layoutCommdityName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.getList(user.getOid());
            }
        });
        myRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (isCanDo) {


                    commodity = (Commodity) adapter.getItem(position);
                    new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE).setTitleText("确定编辑-" + commodity.getName() + "-商品吗？")
                            .setConfirmText("确定").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            editCommdityName.setText(commodity.getName());
                            commodityId = commodity.getId();
                            editCommdityPointe.setText(String.valueOf(commodity.getPoints()));
                            if (editCommdityDialog != null)
                                if (!editCommdityDialog.isShowing())
                                    editCommdityDialog.show();
                            sweetAlertDialog.dismiss();
                            isUpdate = true;
                        }
                    }).setCancelText("取消").setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            isUpdate = false;
                            sweetAlertDialog.dismiss();
                        }
                    }).show();
                }
            }

            @Override
            public void onItemLongClick(BaseQuickAdapter adapter, View view, final int position) {
                super.onItemLongClick(adapter, view, position);
                if (isCanDo) {


                    final Commodity com = (Commodity) adapter.getItem(position);
                    new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE).setTitleText("确定要删除该条记录吗？").setConfirmText("确定").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            showProgressDialog();
                            mPresenter.delPointsCommondity(com.getMaterialId(), position, sweetAlertDialog);
                        }
                    }).setCancelText("取消").show();
                }
            }
        });
    }

    private void initView() {
        setTitleBar(toolbar, "积分商品");
        intent = getIntent();
        bundle = intent.getExtras();
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        moudles = (List<Moudle>) bundle.getSerializable(Constant.PERMISSION_LIST);
        isCanDo = isCanDo(moudles, PermissionConfig.MENU_MAKETING_4);
        if (!isCanDo) {
            addPointCommntiy.setVisibility(View.GONE);
        }
        setRefresh(mySwf);
        initDialog();
        initAdapter();
        addData();
    }

    private void initDialog() {
        listDialog = View.inflate(context, R.layout.dialog_list, null);
        editCommdityDialog = getDialogBuilder(listDialog, R.style.AlertDialog);
        editCommdityDialog.setCanceledOnTouchOutside(false);
        editCommdityName = (TextView) listDialog.findViewById(R.id.edit_commdity_name);
        editCommdityPointe = (MaterialEditText) listDialog.findViewById(R.id.edit_com_pointe);
        layoutCommdityName = (LinearLayout) listDialog.findViewById(R.id.layout_commdity_name);
        cancle = (Button) listDialog.findViewById(R.id.btn_cancle);
        confirm = (Button) listDialog.findViewById(R.id.btn_confirm);
    }

    private void initAdapter() {
        setRecy(myRecycler);
        commondityAdapter = new CommondityAdapter(R.layout.item_point_commondity, new ArrayList<Commodity>());
        commondityAdapter.setEmptyView(emptyView);
        myRecycler.setAdapter(commondityAdapter);
    }

    private void addData() {
        showProgressDialog();
        mPresenter.selectPointsCommondity(user.getOid());
    }

    @OnClick(R.id.add_point_commntiy)
    public void onViewClicked() {
        isUpdate = false;
        editCommdityName.setText(null);
        editCommdityPointe.setText(null);
        commodityId = 0;
        editCommdityDialog.show();
    }

    @Override
    public void setList(List<Commodity> commodityList) {
        dissProgressDialog();
        commondityAdapter.setNewData(commodityList);
    }

    @Override
    public void setcatelist(List<Category> catelist) {
        if (catelist != null) {
            showList(catelist, 0);
        }
    }


    private void showList(final List<?> list, final int type) {
        final String[] strings = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            strings[i] = (type == 0 ? (((Category) list.get(i)).getName()) :
                    (((Commodity) list.get(i)).getName()));
        }
        final Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle(type == 0 ? "选择分类？" : "选择商品？").
                setIcon(R.drawable.ic_launcher)
                .setItems(strings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (type == 0) {
                            mPresenter.getCommDityList(((Category) list.get(which)).getId(), dialog);
                        } else if (type == 1) {
                            commodityId = ((Commodity) list.get(which)).getId();
                            editCommdityName.setText(((Commodity) list.get(which)).getName());
                        }
                    }
                }).setNegativeButton("取消", null).
                        create();
        alertDialog.show();
    }

    @Override
    public void commodityList(List<Commodity> commodityList, DialogInterface dialog) {
        if (commodityList != null) {
            if (commodityList.size() != 0) {
                dialog.dismiss();
                showList(commodityList, 1);
            } else {
                toast("该分类下没有可选商品。");
            }
        } else {
            toast("该分类下没有可选商品。");
        }
    }

    @Override
    public void upRes(int res) {
        dissProgressDialog();
        if (res == 1) {
            editCommdityDialog.dismiss();
            toast(R.string.up_success);
            addData();
        } else {
            toast(R.string.up_failure);
        }
    }

    @Override
    public void delRes(int res, Integer postion, SweetAlertDialog sweetAlertDialog) {
        dissProgressDialog();
        if (res == 1) {
            toast("删除成功");
            sweetAlertDialog.dismiss();
            commondityAdapter.remove(postion);
        } else {
            toast("删除失败，请重试！");
        }
    }
}
